package logic.nodes.collision;


import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;

public class RotationImpulseController extends Controller {
	
	private static final long serialVersionUID = 1L;
	
	private CollidableNode node;
	private Vector3f rotationDir, impulseLoc, currentTargetLoc;
	
	private Vector3f targetLoc1, targetLoc2, targetLoc3, targetLoc4;
	
	private float impulseSpeed;
	private float breaking = 0.02f;
	private Quaternion currentTargetRot;
	
	public RotationImpulseController(CollidableNode node, Vector3f rotationDir, Vector3f impulseLoc, float impulseSpeed) {
		this.node = node;
		this.rotationDir = rotationDir;
		this.impulseLoc = impulseLoc;
		this.impulseSpeed = FastMath.abs(impulseSpeed);
		
		createRotVectors();
	}
	
	private void createRotVectors() {
		Vector3f upVector = node.getUpVector();
		float angle = 90f;
		targetLoc1 = CollidableNode.rotate(upVector, rotationDir, angle).add(impulseLoc);
		targetLoc2 = CollidableNode.rotate(upVector, targetLoc1, angle).add(impulseLoc);
		targetLoc3 = CollidableNode.rotate(upVector, targetLoc2, angle).add(impulseLoc);
		targetLoc4 = CollidableNode.rotate(upVector, targetLoc3, angle).add(impulseLoc);
	}
	
	@Override
	public void update(float time) {
		if(impulseSpeed <= 0f) {
			node.removeRotationImpulseController(this);
			return;
		}
		
		if(currentTargetRot == null || currentTargetRot.equals(node.getLocalRotation())) {
			setTargetLocation();
			
			Quaternion oldRot = new Quaternion(node.getLocalRotation());
			node.lookAt(currentTargetLoc, Vector3f.UNIT_Y);
			
			currentTargetRot = new Quaternion(node.getLocalRotation());
			node.getLocalRotation().set(oldRot);
			
		}
		node.getLocalRotation().slerp(currentTargetRot, time * 1.25f);
		
		impulseSpeed -= breaking;
	}
	
	private void setTargetLocation() {
		if(currentTargetLoc == null || currentTargetLoc == targetLoc4) currentTargetLoc = targetLoc1;
		else if(currentTargetLoc == targetLoc1) currentTargetLoc = targetLoc2;
		else if(currentTargetLoc == targetLoc2) currentTargetLoc = targetLoc3;
		else currentTargetLoc = targetLoc4;
	}
}